<template>
    <div class="direct-plan-add-view view-container">

        <header-module left-custom padding>
            <template #left-con>
                <div>
                    <span style="font-size: 16px; margin-right: 20px">新建商业营销规划</span>
                </div>
            </template>

            <template #btn>
                <el-button class="main-btn" size="small" @click="onBack">返回</el-button>
                <el-button class="main-btn" size="small" type="primary" @click="onSave">保存</el-button>
                <el-button class="main-btn" size="small" type="primary" @click="onAudit">提交审核</el-button>
            </template>

        </header-module>

        <div class="main-content">

            <item-title title="基本信息"/>

            <el-form
                    ref="ruleForm"
                    :inline="true"
                    :model="datas"
                    :rules="rules"
                    class="filter-form-inline"
                    label-position="right"
                    label-width="120px"
                    size="small"
            >
                <el-row :gutter="20">

                    <el-col :span="8">
                        <el-form-item label="关联市场准入" style="width: 100%">

                            <el-input
                                    ref="refInput"
                                    v-model="datas.selectName"
                                    :disabled="list.length > 0"
                                    placeholder="请输入市场准入"
                                    clearable
                                    @clear="chanceClear"
                                    @blur="chanceBlur"
                                    @focus="chanceFocus"
                            />

                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="规划名称" prop="planName" style="width: 100%">
                            <el-input
                                    v-model="datas.planName"
                                    clearable
                                    placeholder="请输入规划名称"
                                    @blur="nameBlur"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="规划结束日期" prop="expireTime" style="width: 100%">
                            <date-picker
                                    v-model:date="datas.expireTime"
                                    :disabled-date="disabledDate"
                                    placeholder="请选择结束日期"
                                    style="width: 100%"
                                    @change="dateChange"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="产品通用名" prop="productPopularName" style="width: 100%">

                            <product-popover
                                    :disabled="disabled || changeChance"
                                    :searchs="datas.productPopularName"
                                    type="4"
                                    @confirm="productConfirm"
                            >
                                <el-input
                                        v-model="datas.productPopularName"
                                        :disabled="datas.chanceId > 0"
                                        placeholder="请输入产品名称"
                                />
                            </product-popover>

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商品名" style="width: 100%">
                            <el-input
                                    v-model="datas.productName"
                                    disabled
                                    placeholder="请选择商品名"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="包装规格" style="width: 100%">
                            <el-input
                                    v-model="datas.packSpecs"
                                    disabled
                                    placeholder="请选择包装规格"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="生产厂家" style="width: 100%">
                            <el-input
                                    v-model="datas.producer"
                                    disabled
                                    placeholder="请选择生产厂家"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="交易价" prop="tradePrice" style="width: 100%">
                            <price-input
                                    style="width: 100%"
                                    v-model:data="datas.tradePrice"
                                    placeholder="请输入交易价"
                                    is-unit
                                    @blur="onBlur"
                                    :unit-str="datas.sellUnit ? '元/' + getLabel('sell_unit',datas.sellUnit) : '元'"
                            />
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>

        </div>

        <chanceDialog ref="chanceDialog" type="4" @confirm="chanceConfirm"/>

    </div>
</template>

<script>
    import chanceDialog from "../../modules/chanceDialog";
    import {useRoute, useRouter} from 'vue-router'
    import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs} from 'vue'

    export default defineComponent({
        name: 'Index',
        components: {
            chanceDialog,
        },
        setup() {
            const currentInstance = getCurrentInstance()
            const route = useRoute()
            const router = useRouter()
            const api = inject('api')
            const rules = ref({
                planName: [
                    {
                        required: true,
                        message: '请输入规划名称',
                        trigger: 'blur',
                    },
                ],
                productPopularName: [
                    {
                        required: true,
                        message: '请选择产品',
                        trigger: 'blur',
                    },
                ],
                expireTime: [
                    {
                        type: 'date',
                        required: true,
                        message: '请选择结束日期',
                        trigger: 'change',
                    },
                ],
                areas: [
                    {
                        required: true,
                        message: '请选择地区',
                        trigger: 'change',
                    },
                ],
                tradePrice: [
                    {
                        required: true,
                        message: '请选择交易价',
                        trigger: 'blur',
                    },
                ],
            })
            const props1 = reactive({
                expandTrigger: 'hover',
                label: 'regionName',
                value: 'regionCode',
            })

            var data = reactive({
                datas: {
                    tradePrice:'',
                    productPriceId:0,
                    accessMode:'',
                    areas:'',
                    region:[],
                    planType: '4',
                    date: '',
                    remark: '',
                    chanceId: 0,
                    chanceName: '',
                    selectName: '',
                    planName: '',
                    expireTime: '',
                    productId: 0,
                    productName: '',
                    packSpecs: '',
                    approvalNumber: '',
                    productPopularName: '',
                    sellUnit: '',
                    files:[],
                },
                list: [],
                disabled: true,
                ChanceInfo: {},
                ruleForm: null,
                chancePop: null,
                changeChance: false,
                chanceDialog: null,
                refInput: null,
                pricePop:null,
                areaOptions:{},
                areaList:[]
            })

            const onBack = () => {
                router.back()
            }

            const onBlur = () => {

            }

            const priceConfirm = (val) => {
                data.datas.productPriceId = val.id
                data.datas.terminalPrice = Number(val.terminalPrice)
                data.datas.accessMode = val.accessMode
            }


            const chanceBlur = () => {
                if (!data.datas.selectName) {
                    data.datas.chanceId = 0
                    data.datas.chanceName = ''
                }
                if (data.datas.chanceName) {
                    data.datas.selectName = data.datas.chanceName
                }
                //data.chancePop.openPopover()
            }

            const chanceFocus = () => {
                // data.chancePop.openPopover()
                data.chanceDialog.openDialog()
                data.refInput.blur()
            }

            const chanceClear = () => {
                data.datas.chanceId = 0
                data.datas.chanceName = ''
                data.datas.selectName = ''
                data.datas.chanceRegion = []
            }

            const chanceConfirm = (item) => {
                data.changeChance = true
                data.datas.chanceId = item.id
                data.datas.chanceName = item.chanceName
                data.datas.selectName = item.chanceName
                data.datas.chanceRegion = item.region
                data.datas.expireTime = item.expireTime

                data.datas.productId = item.productId
                data.datas.productName = item.productName
                data.datas.productPopularName = item.productPopularName
                data.datas.packSpecs = item.packSpecs
                data.datas.producer = item.producer
                data.datas.approvalNumber = item.approvalNumber
                data.datas.sellUnit = item.sellUnit

                setTimeout(() => {
                    data.changeChance = false
                }, 500)
            }

            const onAudit = () => {
                currentInstance.proxy
                    .alertBox({
                        message: '是否提交审核该规划？',
                        title: '审核',
                    })
                    .then(() => {
                        if (checkData()) {
                            saveData().then(() => {
                                audit()
                            }).catch(err => {
                            })
                        }
                    })
                    .catch((err) => {
                        console.log(err)
                    })
            }

            const audit = () => {
                api.plan.PLAN_CHECK_COMMIT({id: data.datas.id}).then((res) => {
                    if (res.code) {
                        currentInstance.proxy.customMessage({type: 'error', message: res.msg})
                    } else {
                        currentInstance.proxy.customMessage({type: 'success', message: '提交成功'})
                        router.back()
                    }
                })
            }

            const onSave = () => {
                if (checkData()) {
                    saveData().then(() => {
                        getData(data.datas.id)
                        currentInstance.proxy.customMessage({type: 'success', message: '保存成功'})
                    }).catch(err => {
                        if (err) {
                            currentInstance.proxy.customMessage({type: 'error', message: err})
                        }
                    })
                }
            }

            const saveData = () => {
                return new Promise((resolve, reject) => {
                    data.datas.tradePrice = Number(data.datas.tradePrice)
                    const postData = {
                        planInfo: {...data.datas},
                        planDetail: data.list,
                        deleteDetailIds: data.deletes
                    }

                    if (route.query.id || data.datas.id) {
                        api.plan.PLAN_EDIT(postData).then(res => {
                            if (!res.code) {
                                resolve()
                            } else {
                                reject(res.msg)
                            }
                        }).catch(err => {
                            reject()
                        })
                    } else {
                        api.plan.PLAN_CREATE(postData).then(res => {
                            if (!res.code) {
                                data.datas.id = res.data.plan.id
                                resolve()
                            } else {
                                reject(res.msg)
                            }
                        }).catch(err => {
                            reject()
                        })
                    }
                })
            }

            const checkData = () => {
                let bo
                data.ruleForm.validate((value) => {
                    if (value) {
                        if (!data.datas.productId) {
                            currentInstance.proxy.customMessage({type: 'error', message: '请选择产品'})
                            bo = false
                            return
                        }
                        bo = true
                    } else {
                        bo = false
                    }
                })
                return bo
            }

            const getData = (id) => {
                api.plan.GET_PLAN_DETAIL({id: id}).then(res => {
                    if (!res.code) {
                        data.deletes = []
                        data.datas = res.data.plan.planInfo
                        data.datas.selectName = data.datas.chanceName

                        setTimeout(() => {
                            data.disabled = false
                        }, 100)
                    } else {
                        currentInstance.proxy.customMessage({type: 'error', message: res.msg})
                    }
                })
            }

            const getChanceData = () => {
                api.chance.CHANCE_DETAIL(route.query.chance_id).then((res) => {
                    if (!res.code && res.data) {
                        data.ChanceInfo = res.data.ChanceInfo

                        data.datas.chanceId = data.ChanceInfo.id
                        data.datas.chanceName = data.ChanceInfo.chanceName
                        data.datas.chanceRegion = data.ChanceInfo.region
                        data.datas.expireTime = data.ChanceInfo.expireTime

                        data.datas.productId = data.ChanceInfo.productId
                        data.datas.productName = data.ChanceInfo.productName
                        data.datas.productPopularName = data.ChanceInfo.productPopularName
                        data.datas.packSpecs = data.ChanceInfo.packSpecs
                        data.datas.approvalNumber = data.ChanceInfo.approvalNumber
                        data.datas.sellUnit = data.ChanceInfo.sellUnit

                    }

                    setTimeout(() => {
                        data.disabled = false
                    }, 100)
                })
            }

            const dateChange = (val) => {

            }

            const productConfirm = (val) => {
                data.datas.productId = val.id
                data.datas.productPopularName = val.productPopularName
                data.datas.productName = val.productName
                data.datas.approvalNumber = val.approvalNumber
                data.datas.packSpecs = val.packSpecs
                data.datas.producer = val.producer
                data.datas.sellUnit = val.sellUnit
            }

            const nameBlur = () => {
                if (data.datas.planName) {
                    const pam = {
                        table: 'plan_info',
                        column: 'plan_name',
                        column_data: data.datas.planName,
                        id: data.datas.id ? data.datas.id : 0,
                    }
                    api.common.COMMON_CHECK_UNIQUE(pam).then((res) => {
                        if (!res.code && res.data) {
                            if (res.data.exist !== '0') {
                                currentInstance.proxy.customMessage({
                                    type: 'error',
                                    message: '名称已重复，请重新输入',
                                })
                            }
                        }
                    })
                }
            }

            const disabledDate = (time) => {
                return !(time.getTime() > Date.now())
            }

            onMounted(() => {
                if (route.query.id) {
                    getData(route.query.id)
                } else if (route.query.chance_id) {
                    getChanceData()
                } else {
                    data.disabled = false
                }
            })

            return {
                ...toRefs(data),
                rules,
                props1,

                disabledDate,
                onBack,
                onSave,
                onAudit,
                nameBlur,
                dateChange,
                productConfirm,
                chanceBlur,
                chanceFocus,
                chanceConfirm,
                priceConfirm,
                onBlur,
                chanceClear,
            }
        }
    })
</script>

<style scoped>

</style>
